Socket
Socket
Sign inDemoInstall

ws

Package Overview
Dependencies
Maintainers
4
Versions
169
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ws

Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js


Version published
Maintainers
4
Created

What is ws?

The 'ws' npm package is a simple to use, fast, and thoroughly tested WebSocket client and server implementation. It provides the necessary tools to build real-time applications with WebSocket support in Node.js.

What are ws's main functionalities?

Creating a WebSocket server

This code sample demonstrates how to create a WebSocket server that listens on port 8080. When a client connects, it sets up an event listener for messages and logs them. It also sends a message 'something' to the client.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });
  ws.send('something');
});

Creating a WebSocket client

This code sample shows how to create a WebSocket client that connects to a WebSocket server. Once the connection is open, it sends a message 'something' to the server and logs any messages received from the server.

const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
  ws.send('something');
});
ws.on('message', function incoming(data) {
  console.log(data);
});

Broadcasting to all clients

This code sample illustrates how to broadcast a message to all connected clients except the sender. It loops through all clients and sends the message if the client is not the sender and the connection is open.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(data) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });
});

Other packages similar to ws

Keywords

FAQs

Package last updated on 16 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc